#!/usr/bin/python
#import section
import os
import sys
import signal
import pygame
pygame.init()

import time
from ship import *
from gamefunctions import *
from alien import *
from menu import *
import speech

#Variable section
#keep track of which section of the game is currently being used
gameState = "start"
#create our ship
player = ship()
#Configuration file
cFile = ".config"
gameLevel = 1
#Make aliens, the number is based on game level.
aliens = []
while len(aliens) < gameLevel * 3:
    aliens.append(alien())

### initialization section ###

# setup handler to catch interrupt sinal so we can exit when the thing crashes
def sigint_handler(signum, stackFrame):
    print "Caught interrupt signal, exiting"
    # TODO: we must have some kind of onexit function to be called here
    # That way we can make some cleanup and such
    pygame.quit()
    sys.exit(1)

signal.signal(signal.SIGINT, sigint_handler)

# Initialize speech
speech.init_speech()


#Start the pygame display
pygame.display.set_mode((320, 200))
#set the window Title
pygame.display.set_caption("Dark Invaders")
#loop until the game is exited.
continueGame = True
msg = "Welcome to Dark Invaders"
speech.speak(msg, False)

while True:
    #run pump once per game loop
    pygame.event.pump()
    # check to see if we need to play a message

    if gameState == "start":
        #start the game with a score of 0.
        player.resetScore()
        gameState = gameMenu()
        continue
    if gameState == "exit": break
    # check for valid keyboard event
    for event in pygame.event.get():
        #if the event is a valid keyboard input, take action based on the gameState variable
        if event.type == pygame.KEYDOWN:
            if gameState == "play":
                if event.key == pygame.K_l: speech.speak("level " + str(gameLevel))
                if event.key == pygame.K_SPACE: player.setFireState(True)
                if event.key == pygame.K_LEFT: player.setDirection(0)
                if event.key == pygame.K_RIGHT: player.setDirection(1)
                if event.key == pygame.K_ESCAPE: gameState = "start"
        elif event.type == pygame.KEYUP:                if event.key == pygame.K_SPACE: player.setFireState(False)
                if event.key == pygame.K_LEFT: player.setDirection(-1)
                if event.key == pygame.K_RIGHT: player.setDirection(-1)
    continueGame = gameAction(player, aliens)
    if len(aliens) <= 0:
        gameLevel += 1
        msg = "level " + str(gameLevel)
        time.sleep(1)
        speech.speak(msg)
        time.sleep(1)
        while len(aliens) < gameLevel * 3:
            aliens.append(alien())
            if len(aliens) >= 25: break
    if player.getHealth() <= 0:
    #Game is over, reset variables.
        gameState = "start"
        player.setHealth(100)
        gameLevel = 1
        while len(aliens) > gameLevel * 3:
            del aliens[0]
            time.sleep(1)
        msg = "You scored " + str(player.getScore()) + "points."
        if player.getScore() >= 500:
            msg += "Post this score on Twitter?"
        speech.speak(msg)
        if player.score >= 500:
            answer = getChoice()
        else:
            answer = False
        if answer == True:
            twitterName = getVar(cFile, "twitter", "username")
            twitterPassword = getVar(cFile, "twitter", "password")
            if twitterName == "" and twitterPassword == "":
                getTwitter()
                twitterName = getVar(cFile, "twitter", "username")
                twitterPassword = getVar(cFile, "twitter", "password")
            if twitterName != "" and twitterPassword != "":
                tweet(twitterName,twitterPassword,player.getScore())
                msg = "Score posted to twitter."
                speech.speak(msg, False)

msg = "Thanks for playing, goodbye."
speech.speak(msg, False)
sys.exit(0)

